package com.goodboys.base.interceptor;

import com.goodboys.base.resp.Response;
import com.goodboys.base.utils.RedisClient;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class JwtInterceptorConifg  implements HandlerInterceptor {

    @Autowired
    private RedisClient redisClient;

    private static final Logger logger = LoggerFactory.getLogger(JwtInterceptorConifg.class);

    /**
     * 进入controller层之前拦截请求
     * @param request
     * @param response
     * @param o
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {

        logger.info("---------------------开始进入请求地址拦截----------------------------");
        //逻辑判断
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("utf-8");
        Response msg = new Response();

        final String authHeader = request.getHeader("authorization");

        if ("OPTIONS".equals(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }
        // Except OPTIONS, other request should be checked by JWT
        else {
            // Check the authorization, check if the token is started by "Bearer "
            if (authHeader == null || !authHeader.startsWith("Bearer ")) {
                msg.failure("请先登录。。。");
                BaseInterceptorConfig.sendMessage(response, msg);
                logger.warn("请先登录。。。");
                return false;
            }

            // Then get the JWT token from authorization
            final String token = authHeader.substring(7);

            try {
                // Use JWT parser to check if the signature is valid with the Key "secretkey"
                final Claims claims = Jwts.parser().setSigningKey("secretkey").parseClaimsJws(token).getBody();

                //判断该用户信息是否正确

                //token设置失效时间，需要重新登录
                try {
                    if (!redisClient.isExistKey("token:" + authHeader)) {
                        msg.failure("登录过期，请重新登录。。。");
                        BaseInterceptorConfig.sendMessage(response, msg);
                        logger.warn("登录过期，请重新登录。。。");
                        return false;
                    }
                } catch (NullPointerException e) {
                    e.printStackTrace();
                }
                request.setAttribute("claims", claims);
            } catch (final SignatureException e) {
                msg.failure("登录信息有误。。。");
                BaseInterceptorConfig.sendMessage(response, msg);
                logger.warn("登录信息有误。。。");
                return false;
            }
            return true;
        }
    }


    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        logger.info("--------------处理请求完成后视图渲染之前的处理操作---------------");
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        logger.info("---------------视图渲染之后的操作-------------------------0");
    }

}
